<?php
/**
 * api 购物车模型类
 * @Author: phpzhi <phpzhi@qq.com><https://www.phpzhi.com>
 * @Date: 2019/11/8 12:59
 */

namespace app\api\model\goods;

use app\api\model\goods\Goods;
use think\Db;
use think\Exception;

class GoodsCart extends \app\common\model\order\GoodsCart
{
    private static $errMsg;
    const DEFAULT_ERR_MSG = '操作失败，请稍候再试';

    protected static function setErrorInfo($errMsg = self::DEFAULT_ERR_MSG, $rollback = false)
    {
        if ($rollback) Db::rollback();
        self::$errMsg = $errMsg;
        return false;
    }

    /**
     * 获取错误信息
     * @param string $defaultMsg
     * @return string
     */
    public static function getErrorInfo($defaultMsg = self::DEFAULT_ERR_MSG)
    {
        return !empty(self::$errMsg) ? self::$errMsg : $defaultMsg;
    }


    /**
     * 添加购物车
     * @param $user_id
     * @param $goods_id
     * @param $cart_num
     * @param $goods_spec_value
     * @param int $is_new
     * @return GoodsCart|array|false|\PDOStatement|string|\think\Model
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function createCart($user_id, $goods_id, $cart_num, $goods_spec_value, $is_new = 0)
    {
        if ($cart_num < 1) $cart_num = 1;
        if (!Goods::isValidGoods($goods_id)) {
            self::setErrorInfo('该产品已下架或已被删除');
        }
        if (Goods::getGoodsStock($goods_id, $goods_spec_value) < $cart_num) {
            self::setErrorInfo('该产品库存不足' . $cart_num);
        }
        /* 规格存在的直接更新 */
        if($cart = self::where(['user_id' => $user_id])->where(['is_new' => $is_new])->where(['is_pay' => 0])->where(['is_del' => 0])->where(['goods_spec_value' => $goods_spec_value])->find()) {
            if ($is_new) {
                $cart['cart_num'] = $cart_num;
            } else {
                $cart['cart_num'] = bcadd($cart_num, $cart['cart_num'], 0); // 累加
            }
            $cart->save();
            Db::rollback();
            return $cart;
        } else {
            $type = 'goods';
            return self::create(compact('user_id', 'goods_id', 'goods_spec_value', 'cart_num', 'is_new', 'type'));
        }
    }

    /**
     * 获取购物车数量
     * @param $userId
     * @param $type
     * @param $numType
     * @return float|int|string
     * @throws Exception
     */
    public static function getUserCartNum($userId, $type, $numType)
    {
        if ($numType) {
            return self::where('id', $userId)->where('type', $type)->where('is_pay', 0)->where('is_del', 0)->where('is_new', 0)->count();
        } else {
            return self::where('id', $userId)->where('type', $type)->where('is_pay', 0)->where('is_del', 0)->where('is_new', 0)->sum('cart_num');
        }
    }

    /**
     * 1.检查是立即购买还是购物车购买
     * 2.检查商品是否存在，不存在则将购物车删除
     * 3.检查商品是否删除，是否有库存
     * 4.检查购买的商品规格是否与规格表一致
     * @param $userId
     * @param $cartIds
     * @param int $status
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserCartList($userId, $cartIds, $status = 0)
    {
        $model = new self(); $valid = $invalid = [];
        $model = $model->where(['user_id' => $userId, 'type' => 'goods', 'is_pay' => 0, 'is_del' => 0]);
        if (!$status) $model = $model->where(['is_new' => 0]);
        if ($cartIds) $model = $model->where('id', 'IN', $cartIds);
        $list = collection((array)$model->order('createtime DESC')->select())->toArray();
        if (!count($list)) return compact('valid', 'invalid');

        foreach ($list as $key => $value) {
            $goodsInfo = Goods::findOne($value['goods_id']); // 商品信息
            halt($goodsInfo);
            $goodsSpec = Goods::getGoodsSpec($value['goods_id'], $value['goods_spec_value']); // 商品对应的规格
            $value['goodsInfo'] = $goodsInfo;
            if (!$goodsInfo) { // 商品不存在
                $model->where(['id' => $value['id']])->update(['is_del' => 1]);
            } else if (!$goodsInfo['status'] || $goodsInfo['is_del'] || !$goodsInfo['spec']['stock_num']) { // 商品已被删除或无库存
                $invalid[] = $value;
            } else if ($goodsInfo['deduct_stock_type'] == 20 && !$goodsSpec) { //多规格商品属性是否存在
                $invalid[] = $value['goods_id'];
            } else {
                $valid[] = $value;
            }

        }

        return compact('valid', 'invalid');
    }
}